var Promise = require('bluebird');
var cheerio = require('cheerio');
var _ = require('lodash');

var mongoBase = require('./mongo-base');
var requestBase = require('./request-base');

module.exports = {
  getListData: getListData,
  getPlaneData: getPlaneData,
  getPlaneArticleData: getPlaneArticleData
};

var url = 'http://sky.news.sina.com.cn/aviation/';


function getListData(urlIdx) {

  var aLinks = [];

  return requestBase.requestData(url)
    .then(function(data) {
      var $ = cheerio.load(data);
      $('table.air-type').find('a').each(function() {
        var link = $(this).attr('href');
        if(/^http:\/\/mil\.news\.sina\.com\.cn\/aviation\/\d+\/\d+\.html$/.test(link)) {
          aLinks.push(link);
        }
      });
    })

    .then(function() {
      var promiseArr = [];
      _.forEach(aLinks, function(link) {
        promiseArr.push(getPlaneData(link));
      });
      return Promise.all(promiseArr)
    })

    .catch(function(err) {
      console.log(err);
    });

}

function getPlaneData(url) {
  var $ = {};
  var planeData = {};

  return requestBase.requestBufferData(url, 'GBK')
    .then(function(data) {
      $ = cheerio.load(data, {decodeEntities: false});
    })

    .then(function() {
      var $Wrap = $('#wrap');

      var $PartA = $Wrap.find('.PartA');
      var $PartB = $Wrap.find('.PartB');
      var $PartD = $Wrap.find('.PartD');

      var name = $PartA.find('.right h1').html();
      var parameters = [];

      var manufacturer = $PartA.find('.info .r1').html().split('：');
      var firstTime = $PartA.find('.info .r2').html().split('：');
      // parameters.push({
      //     name: manufacturer[0],
      //     value: manufacturer[1]
      // });
      // parameters.push({
      //     name: firstTime[0],
      //     value: firstTime[1]
      // });

      $PartA.find('.right td').each(function() {
        var attrArr = $(this).html().substring(8).split('</strong>：');
        parameters.push({
          name: attrArr[0],
          value: attrArr[1]
        })
      });

      var scriptString = $PartA.find('.left script').html();
      var idxStart = scriptString.indexOf('\/\/var pics=\'') + 10;
      idxStart = scriptString.indexOf('var pics=\'', idxStart) + 10;
      var idxEnd = scriptString.indexOf('\';', idxStart);
      var photos = scriptString.substring(idxStart, idxEnd).split('|');
      
      var detailLink = '';
      var $ellipsis = $PartB.find('p');
      $ellipsis.find('a').each(function() {
        var link = $(this).attr('href');
        if(/^http:\/\/\w+\.news\.sina\.com\.cn\D*\/*\d+-\d+-\d+\/\d+\.html$/.test(link)) {
          detailLink = link;
        }
        $(this).remove();
      });
      var ellipsis = $ellipsis.html();

      var others = [];
      $PartD.find('tr').each(function() {
        var name = $(this).find('.td_1').html();
        var description = $(this).find('.td_2').html();
        if(name && description) {
          others.push({name: name, description: description});
        }
      });

      planeData = {
        planeName: name,
        manufacturer: manufacturer[1],
        firstTime: firstTime[1],
        parameters: parameters,
        photos: photos,
        ellipsis: ellipsis.substring(0, ellipsis.length - 6),
        detailLink: detailLink,
        others: others,
        detailKey: '',
        date: new Date()
      };

    })
    
    .then(function() {
      if(!planeData.detailLink) {
        console.log('detailLink is null ' + url);
        return;
      }
      return getPlaneArticleData(planeData.detailLink);
    })

    .then(function(data) {
      if(data && data._id) {
        planeData.detailKey = data._id;
      }

      var query = {'planeName': planeData.planeName};
      var fields = {_id:1};
      return mongoBase.findOneData('plane-data', query, fields);
    })

    .then(function(data) {
      if(data && data._id) {
        return mongoBase.updateData('plane-data', {_id: data._id}, planeData);
      } else {
        return mongoBase.saveData('plane-data', planeData);
      }
    })

    .catch(function(err) {
      console.log(err);
    });

}


function getPlaneArticleData(url) {
  var $ = {};
  var articleData = {};

  return requestBase.requestBufferData(url, 'GBK')
    .then(function(data) {
      $ = cheerio.load(data, {decodeEntities: false});
    })

    .then(function() {

      var $artibodyTitle = $('#artibodyTitle');
      var $fromInfo = $('.from_info');
      var $mediaName = $fromInfo.find('.linkRed02 a');
      var $artibody = $('#artibody');

      $fromInfo.find('.linkRed02').remove();
      var fromInfoStr = $fromInfo.html();
      var pubDate = '';
      if(fromInfoStr) {
        pubDate = fromInfoStr.substring(fromInfoStr.indexOf('\n') + 2).trim();
      } else {
        pubDate = $('#pub_date').html();
      }
      var date = new Date(Date.parse(pubDate.replace('年','-').replace('月','-').replace('日','')));

      articleData = {
        originalLink: url,
        artibodyTitle: $artibodyTitle.find('h1').html() ? $artibodyTitle.find('h1').html() : $artibodyTitle.html(),
        mediaName: $mediaName.html() ? $mediaName.html() : $('#media_name').html(),
        medialink: $mediaName.attr('href') ? $mediaName.attr('href') : 'javascript:void(0)',
        artibody: $artibody.html(),
        pubDate: pubDate,
        date: date
      };
    })

    .then(function() {
      var query = {'artibodyTitle': articleData.artibodyTitle};
      var fields = {_id:1};
      return mongoBase.findOneData('plane-article', query, fields);
    })

    .then(function(data) {
      if(data && data._id) {
        return mongoBase.updateData('plane-data', {_id: data._id}, articleData);
      } else {
        return mongoBase.saveData('plane-article', articleData);
      }
    })

    .catch(function(err) {
      console.log(err);
    });

}